from cocos.layer import Layer
import pyglet


def symbol_key_name(key):
    return pyglet.window.key.symbol_string(key)


class Keyboard(Layer):
    is_event_handler = True

    def __init__(self, key_press_callback=None):
        super(Keyboard, self).__init__()
        self._keys_pressed = set()
        self._key_press_callback = key_press_callback

    def on_key_press(self, key, modifiers):
        """This function is called when a key is pressed.
        'key' is a constant indicating which key was pressed.
        'modifiers' is a bitwise or of several constants indicating which
            modifiers are active at the time of the press (ctrl, shift, capslock, etc.)
        """

        self._keys_pressed.add(key)
        if self._key_press_callback:
            self._key_press_callback(symbol_key_name(key))

    def on_key_release(self, key, modifiers):
        """This function is called when a key is released. 

        'key' is a constant indicating which key was pressed.
        'modifiers' is a bitwise or of several constants indicating which
            modifiers are active at the time of the press (ctrl, shift, capslock, etc.)

        Constants are the ones from pyglet.window.key
        """

        if key in self._keys_pressed:
            self._keys_pressed.remove(key)

    def clear_keys(self):
        self._keys_pressed.clear()

    def get_keys(self):
        return [symbol_key_name(k) for k in self._keys_pressed]
